﻿/*
 * This software is the confidential and proprietary
 * information of NetBay
 * Such confidential information should not be disclosed
 * NetBay copyright(c) 2010
 */

#region using
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using NetBay.Core.Silverlight.Log;
using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.AppCode.Helpers;
using Rio.Framework.Pages.Context;
using Rio.Framework.Pages.Helpers;
using Rio.Framework.Pages.Helpers.Utils;
using Rio.Framework.Pages.Manager;
using Rio.Framework.Pages.UserControls;
using Rio.Framework.WCFService;
using Rio.Framework.WCFService.RioWcfServices;
using Telerik.Windows;
using Telerik.Windows.Controls.DragDrop;
using Document = NetBay.Core.BusinessEntities.Document;
using RadContextMenu = Telerik.Windows.Controls.RadContextMenu;
using Rio.Framework.Pages.AppCode.Enums;
#endregion

namespace Rio.Framework.Pages.Viewer
{
    public partial class ThumbnailPanel
    {
        #region Attributs

        PostManyDocument m_oPostManyDocument;
        private IEnumerable<FileInfo> m_oImportFile = null;

        // Number of imported file
        public int m_iNbrImportFile;
        private string m_sMsgFileCompatible = string.Empty;

        // Count of posted document
        public int m_iCountPostedDocument;
        // List of imported file name
        public List<string> m_oImportedImageFileName = new List<string>();
        private string m_sMsgIsImporting = string.Empty;

        private int m_iNbDocToLoad = 0;
        private int m_iNbDocToLoad_OK = 0;
        private int m_iNbDocToLoad_KO = 0;
        private List<String> m_oFilenamOnError = null;
        private string m_sMsgTransferErrorHeader;
        private string m_sMsgTransferError;

        public event EventHandler RefreshViewerAfterIndex;
        public event EventHandler ImportFilesAfterLoadVignettes;
        private bool m_bRefreshViewer;

        private readonly string[] m_aFileFiltersGranted = {
                                              ".JPEG",
                                              ".JPG",
                                              ".TIFF",
                                              ".TIF",
                                              ".PDF",
                                              ".BMP",
                                              ".DOC",
                                              ".DOCX",
                                              ".XLS",
                                              ".XLSX",
                                              ".PPT",
                                              ".PPTX",
                                              ".RTF",
                                              ".TXT",
                                              ".GIF",
                                              ".PNG",
                                              ".ZIP"
                                          };


        // Prompt this message for user when a merge pdf operation is requested
        protected string LabelExplodePdfQuestion { get; set; }


        /// <summary>
        /// This field is used to store the list of filename of document to convert though WF Service (ConvertDocumentAppend)
        /// </summary>
        private List<string> m_oFilenamesToConvert = new List<string>();

        /// <summary>
        /// This field is used to initialize a documents convert. At each conerting, a new guid is generated.
        /// </summary>
        private Guid m_oGuidSessionToConvert;

        /// <summary>
        /// This field is used to store the list of filenames of documents to delete
        /// </summary>
        private Stack<String> m_oFilenamesToDelete = new Stack<string>();

        /// <summary>
        /// This field is use to store the list of filenames of documents which an error has occured during deleting.
        /// </summary>
        private List<String> m_oFilenamesErrorDuringDeleting = new List<string>();

        #endregion

        #region Properties 

        /// <summary>
        /// Gets or sets the list item source.
        /// </summary>
        /// <value>The list item source.</value>
        public ObservableCollection<ImageRio> ListItemSource
        {
            get
            {
                return m_oItemsSource;
            }
            set
            {
                m_oItemsSource = value;
                OnPropertyChanged("ListItemSource");
            }
        }

        public override bool ScanImportIsEnabled
        {
            get
            {
                return base.ScanImportIsEnabled;
            }
            set
            {
                base.ScanImportIsEnabled = value;
                if (DocumentToolbar != null)
                {
                    DocumentToolbar.ScanImportIsEnabled = value;
                    DocumentToolbar.ManageToolbar();
                }
            }
        }

        /// <summary>
        /// List of current selected files
        /// </summary>
        public List<string> SelectedFilenames { get; set; }

        /// <summary>
        /// This property is used to define the maximum number of files allowed in OpenFileDialog
        /// </summary>
        public int MaxNumberOfFilesImported { get; set; }

        /// <summary>
        /// Get or set the current selected thumbnail
        /// </summary>
        public override ImageRio CurrentSelectedImage
        {
            get
            {
                if (ListBoxVignette.SelectedItem != null && ListBoxVignette.SelectedItems.Count >= 1)
                {
                    base.CurrentSelectedImage = (ImageRio)ListBoxVignette.SelectedItems[0];
                }
                return base.CurrentSelectedImage;
            }
            set
            {
                base.CurrentSelectedImage = value;
            }
        }

        /// <summary>
        /// Get or set a list of all thumbnail
        /// </summary>
        public override IList<ImageRio> RioImageList
        {
            get
            {
                if (ListBoxVignette.SelectedItem != null && ListBoxVignette.SelectedItems.Count >= 1)
                {
                    base.RioImageList = ListBoxVignette.SelectedItems as IList<ImageRio>;
                }
                return base.RioImageList;
            }
            set
            {
                base.RioImageList = value;
            }
        }

        /// <summary>
        /// Used to set the order of files
        /// </summary>
        public bool FileInPostOrder { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ThumbnailPanel" /> class.
        /// </summary>
        public ThumbnailPanel()
        {
            InitializeComponent();

            InitLabel();
            SmartDispatcher.Initialize();
            m_oItemsSource = new ObservableCollection<ImageRio>();
            ImportedDocumentMergedFailed += ThumbnailPanel_ImportedDocumentMergedFailed;

            //Initialize document toolbar
            DocumentToolbar.AppDisplayMode = AppDisplayMode.None;
            DocumentToolbar.ViewMode = AppViewMode.Thumbnail;
            DocumentToolbar.DocumentRibbonBarEvent += DocumentToolbar_DocumentRibbonBarEvent;
            DocumentToolbar.ManageToolbar();

            //Init document context menu
            DocumentContextMenu.AppDisplayMode = AppDisplayMode.None;
            RadContextMenu.SetContextMenu(ListBoxVignette, DocumentContextMenu.ContextMenu);
            DocumentContextMenu.ViewMode = AppViewMode.Thumbnail;
            DocumentContextMenu.ManageContextMenuItemState();
            DocumentContextMenu.DocumentContextMenuEvent += DocumentToolbar_DocumentRibbonBarEvent;

            //Events for drag and drop
            ListBoxVignette.AddHandler(RadDragAndDropManager.DropQueryEvent, new EventHandler<DragDropQueryEventArgs>(OnDropQuery));
            ListBoxVignette.AddHandler(RadDragAndDropManager.DragQueryEvent, new EventHandler<DragDropQueryEventArgs>(OnDragQuery));
            ListBoxVignette.AddHandler(RadDragAndDropManager.DropInfoEvent, new EventHandler<DragDropEventArgs>(OnDropInfo));
        }

        #endregion

        #region Document Toolbar

        /// <summary>
        /// Handles the DocumentRibbonBarEvent event of the DocumentToolbar control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="Rio.Framework.Pages.Events.DocumentRibbonBarEventArgs" /> instance containing the event data.</param>
        private void DocumentToolbar_DocumentRibbonBarEvent(object sender, Events.DocumentRibbonBarEventArgs args)
        {
            switch (args.DocumentRibbonBarMenuItem)
            {
                #region ScanImport
                case AppCode.Enums.DocumentRibbonBarMenuItems.Scan:
                    OnScanRequest();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Import:
                    OnImportRequest();
                    break;
                #endregion

                #region Selection
                case AppCode.Enums.DocumentRibbonBarMenuItems.SelectAll:
                    OnSelectAll();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.SelectNone:
                    OnSelectNone();
                    break;
                #endregion

                #region Display Mode
                case AppCode.Enums.DocumentRibbonBarMenuItems.DocumentMode:
                    DocumentContextMenu.ManageContextMenuItemState();
                    DocumentToolbar.ManageToolbar();
                    DocumentToolbar.HideMinimizedPopup();
                    SaveModificationOnImage(ClickEvent.Viewer);
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.ThumbnailsMode:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.ListMode:
                    DocumentContextMenu.ManageContextMenuItemState();
                    DocumentToolbar.ManageToolbar();
                    DocumentToolbar.HideMinimizedPopup();
                    SaveModificationOnImage(ClickEvent.List);
                    break;
                #endregion

                #region Fitting
                case AppCode.Enums.DocumentRibbonBarMenuItems.FitHeight:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.FitWidth:
                    break;

                #endregion

                #region Zoom
                case AppCode.Enums.DocumentRibbonBarMenuItems.ZoomIn:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.ZoomOut:
                    break;
                #endregion

                #region Rotate
                case AppCode.Enums.DocumentRibbonBarMenuItems.RotateLeft:
                    OnRotateLeft();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.RotateRight:
                    OnRotateRight();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.SaveModifications:
                    SaveModificationOnThumbNails(ListBoxVignette.SelectedItems);
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.SplitPDF:
                    OnExplodePDF();
                    break;
                #endregion

                #region Search
                case AppCode.Enums.DocumentRibbonBarMenuItems.SearchNext:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.SearchPrevious:
                    break;
                #endregion

                #region Actions
                case AppCode.Enums.DocumentRibbonBarMenuItems.SendEmail:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Delete:
                    OnItemDelete();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.MergePDF:
                    OnMergePDF();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Download:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Print:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Split2:
                    m_bRefreshViewer = true;
                    if (CurrentSelectedImage != null && CurrentSelectedImage.NumberPages <= 1) OnSplitImage(Utils.RemoveExtension(CurrentSelectedImage.Name), 2);
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Split3:
                    m_bRefreshViewer = true;
                    if (CurrentSelectedImage != null && CurrentSelectedImage.NumberPages <= 1) OnSplitImage(Utils.RemoveExtension(CurrentSelectedImage.Name), 3);
                    break;

                #endregion

                #region Edit
                case AppCode.Enums.DocumentRibbonBarMenuItems.Cut:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Copy:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Paste:
                    break;
                #endregion

                #region Workflow
                case AppCode.Enums.DocumentRibbonBarMenuItems.Ventilate:
                    break;
                #endregion

                #region Outlook
                case AppCode.Enums.DocumentRibbonBarMenuItems.OpenDirectory:
                    OnOpenDirectory();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.ReturnDirectory:
                    OnReturnDirectory();
                    break;

                #endregion
            }
        }

        #endregion

        #region Selected vignette item event to display

        /// <summary>
        /// Click on listbox's item
        /// If it's a double click, we raise an event: "itemSelected"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Item_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2)
            {
                if (CurrentSelectedImage != null)
                {
                    //Selected thumbnail is not a directory
                    if (!CurrentSelectedImage.isDirectory)
                    {
                        GetFileNameSelected = Utils.RemoveExtension(CurrentSelectedImage.Name);
                        SaveModificationOnImage(ClickEvent.ListBoxItemChange);
                    }
                    else if (CurrentSelectedImage.isDirectory)
                    {
                        //Show document inside the current selected directory
                        CurrentSelectedDirectory = CurrentSelectedImage.Name;
                        SaveModificationOnImage(ClickEvent.OpenDirectory);
                    }
                }
            }
        }

        #endregion

        #region Selected vignette items event

        /// <summary>
        /// Occurs when a thumbnail is selected
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListBoxVignette_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SelectedDocumentIndex = ListBoxVignette.SelectedIndex;
            int L_iInsertIndex;
            SelectedFilenames = new List<string>();
            _selectedImages = new List<ImageRio>();

            //Reorder the selected item in high to read
            if ((ListBoxVignette.SelectedItems != null) && (ListBoxVignette.SelectedItems.Count > 0))
            {
                foreach (ImageRio itemSelected in ListBoxVignette.SelectedItems)
                {
                    L_iInsertIndex = -1;

                    foreach (ImageRio item in _selectedImages)
                    {
                        if (ListBoxVignette.Items.IndexOf(itemSelected) < ListBoxVignette.Items.IndexOf(item))
                        {
                            L_iInsertIndex = _selectedImages.IndexOf(item);
                            break;
                        }
                    }

                    if (L_iInsertIndex.Equals(-1))
                    {
                        _selectedImages.Add(itemSelected);
                        SelectedFilenames.Add(Utils.RemoveExtension(itemSelected.Name));
                    }
                    else
                    {
                        _selectedImages.Insert(L_iInsertIndex, itemSelected);
                        SelectedFilenames.Insert(L_iInsertIndex, Utils.RemoveExtension(itemSelected.Name));
                    }
                }
            }

            //toolbar state
            ManageToolbarState();

            //raise correct event
            if (CurrentSelectedImage != null && CurrentSelectedImage.isDirectory)
            {
                OnDirectorySelected();
            }
            else
            {
                OnItemsSelected(SelectedFilenames);
            }
        }

        /// <summary>
        /// Used to perform rightclick selection
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListBoxVignette_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        /// <summary>
        ///  Used to perform rightclick selection
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListBoxVignette_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            try
            {

                //ListBoxVignette.SelectedItem = null;
                //VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), (sender as ListBox)).OfType<ListBoxItem>().First().IsSelected = true;
            }
            catch
            {
                
            }
        }

        /// <summary>
        /// Use to delete item
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListBoxVignette_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                OnItemDelete();
            }
        }

        /// <summary>
        /// This event is called by the Listbox on external drag and drop.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListBoxVignette_Drop(object sender, DragEventArgs e)
        {
            IDataObject data = e.Data;
            if (data.GetDataPresent(DataFormats.FileDrop))
            {
                FileInfo[] files = data.GetData(DataFormats.FileDrop) as FileInfo[];
                ImportFiles(files);
            }
        }

        #endregion

        #region Load and refresh vignettes

        /// <summary>
        /// Loads the vignette and import.
        /// </summary>
        /// <param name="p_oFilesToImport">The p_o files to import.</param>
        public void LoadVignetteAndImport(IEnumerable<FileInfo> p_oFilesToImport)
        {
            m_oImportFile = p_oFilesToImport;
            this.ImportFilesAfterLoadVignettes += ThumbnailPanel_ImportFilesAfterLoadVignettes;
            LoadVignettes();
        }

        /// <summary>
        /// Handles the ImportFilesAfterLoadVignettes event of the ThumbnailPanel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        void ThumbnailPanel_ImportFilesAfterLoadVignettes(object sender, EventArgs e) 
        {
            ImportFiles(m_oImportFile);
        }

        /// <summary>
        /// Load vignettes
        /// </summary>
        /// <param name="L_iSelectedViewerDocIndex">Index of the l_i selected viewer doc.</param>
        /// <param name="p_bRefreshViewer">The P_B refresh viewer.</param>
        /// <param name="manageToolbarState">if set to <c>true</c> [manage toolbar state].</param>
        public void LoadVignettes(int L_iSelectedViewerDocIndex = -1, bool p_bRefreshViewer = false, bool manageToolbarState = true)
        {
            m_bRefreshViewer = p_bRefreshViewer;

            //refresh
            RefreshImportedDocuments(L_iSelectedViewerDocIndex);

            if (manageToolbarState)
                ManageToolbarState();
        }

        /// <summary>
        /// Handles the ImportedDocumentRefreshed event
        /// </summary>
        /// <param name="p_oImageRioCollection">The p_o image rio collection.</param>
        public void ThumbnailPanel_ImportedDocumentRefreshed(ObservableCollection<ImageRio> p_oImageRioCollection)
        {
            ListItemSource = new ObservableCollection<ImageRio>(ManageDocumentListRank(p_oImageRioCollection));
            TextBlockMode.Visibility = ListBoxVignette.Items.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
            if (m_iSelectedViewerDocIndex != -1)
            {
                if ((ListBoxVignette != null) && (ListBoxVignette.Items.Count > 0) && (m_iSelectedViewerDocIndex < ListBoxVignette.Items.Count))
                {
                    ListBoxVignette.SelectedIndex = m_iSelectedViewerDocIndex;
                }
            }
            else
            {
                if ((ListBoxVignette != null) && (ListBoxVignette.Items.Count > 0))
                {
                    ListBoxVignette.SelectedIndex = 0;
                }
            }
            CursorNormal(this);

            if (m_bRefreshViewer)
            {
                OnRefreshViewer();
            }

            if (ImportFilesAfterLoadVignettes != null)
            {
                ImportFilesAfterLoadVignettes(this, null);
            }

            OnRefreshThumbnails();

            ManageToolbarState();
        }

        /// <summary>
        /// Loaded control
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs" /> instance containing the event data.</param>
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            CursorWait(this);
            LoadVignettes(-1, false,false);
            ListBoxVignette.Focus();
            FireOnInitialisationCompleted();
        }

        #endregion

        #region MergePDF


        /// <summary>
        /// Handles the RefreshThumbnails event of the ThumbnailPanel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        private void ThumbnailPanel_RefreshThumbnails(object sender, EventArgs e)
        {
            RefreshThumbnails -= ThumbnailPanel_RefreshThumbnails;

            LoadVignettes();
        }

        /// <summary>
        /// Handles the ConvertDocumentFinishCompleted event of the L_oWCFServiceClient control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rio.Framework.WCFService.RioWcfServices.ConvertDocumentFinishCompletedEventArgs"/> instance containing the event data.</param>
        private void L_oWCFServiceClient_ConvertDocumentFinishCompleted(object sender, ConvertDocumentFinishCompletedEventArgs e)
        {
            WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();

            SplashScreenManager.SplashScreen.ProgressBarProcess.Visibility = Visibility.Collapsed;
            SplashScreenManager.SplashScreen.ProgressBarProcess.Value = 0;

            //Delete temporary directory
            L_oWCFServiceClient.DeleteTemporaryDirectoryCompleted += (s, ev) =>
            {
                //Delete all imported documen who have been converted
                L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();

                L_oWCFServiceClient.DeleteImportDocumentCompleted += (o, ew) =>
                {
                    m_oFilenamesToConvert.Clear();

                    LoadVignettes();

                    CursorNormal(this);
                };

                L_oWCFServiceClient.DeleteImportDocumentAsync(new ObservableCollection<string>(m_oFilenamesToConvert), UserId, ServiceManager.GetLicenseKey());
            };

            L_oWCFServiceClient.DeleteTemporaryDirectoryAsync(m_oGuidSessionToConvert.ToString("N"), ServiceManager.GetLicenseKey());
        }


        /// <summary>
        /// Handles the ImportedDocumentMergedFailed event of the ThumbnailPanel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        private void ThumbnailPanel_ImportedDocumentMergedFailed(object sender, EventArgs e)
        {
            LoadVignettes();
        }


        #endregion

        #region Explode PDF

        /// <summary>
        /// Callback Display ExpodePDF
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void L_oWCFServiceClient_ExplodePDFCompleted(object sender, ExplodePdfCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                GetThumbnailList(-1, this.CurrentSelectedDirectory);
            }

        }

        #endregion

        #region Toolbar menu

        /// <summary>
        /// Merge document into a pdf from the selected thumbnail
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnMergePDF()
        {
            RefreshThumbnails += ThumbnailPanel_RefreshThumbnails;
            SetActuallyRankingList();
            if (SelectedImages != null && SelectedImages.Count > 0)
            {
                SaveModificationOnThumbNails(SelectedImages, true);
            }
            else
            {
                SaveModificationOnThumbNails(ListBoxVignette.SelectedItems, true);
            }
        }

        /// <summary>
        /// Called when [item delete click].
        /// </summary>
        private void OnItemDelete()
        {
            ImportedDocumentDeleted += (e) =>
                {
                    ListItemSource.Remove(e);

                    TextBlockMode.Visibility = ListBoxVignette.Items.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
                };

            DeleteImportedDocuments(ListBoxVignette.SelectedItems.Cast<ImageRio>().ToList());
        }

        /// <summary>
        /// Called when [refresh viewer].
        /// </summary>
        public void OnRefreshViewer()
        {
            if (RefreshViewerAfterIndex != null)
            {
                m_bRefreshViewer = false;
                RefreshViewerAfterIndex(this, null);
            }
        }

        /// <summary>
        /// Click on Return Directory button
        /// </summary>
        private void OnReturnDirectory()
        {
            SaveModificationOnImage(ClickEvent.ReturnDirectory);
        }

        /// <summary>
        /// Open th selected directory
        /// </summary>
        private void OnOpenDirectory()
        {
            SaveModificationOnImage(ClickEvent.OpenDirectory);
        }

        /// <summary>
        /// Selects the all_ click.
        /// </summary>
        private void OnSelectAll()
        {
            ListBoxVignette.SelectAll();
            ListBoxVignette.Focus();
        }

        /// <summary>
        /// Selects the none_ click.
        /// </summary>
        private void OnSelectNone()
        {
            ListBoxVignette.SelectedItems.Clear();
        }

        /// <summary>
        /// Dispatch Page/Page file PDF
        /// </summary>
        private void OnExplodePDF()
        {


            MessageBoxChildWindow L_oMessagesExplodePdf = new MessageBoxChildWindow("",LabelExplodePdfQuestion, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            L_oMessagesExplodePdf.Show();
            L_oMessagesExplodePdf.Closed += (s, ev) =>
                {
                    if (L_oMessagesExplodePdf.Result == MessageBoxResult.Yes)
                    {
                        CursorWait(this);
                        foreach (ImageRio itemVignette in ListBoxVignette.SelectedItems)
                        {
                            string l_szFileName = Utils.RemoveExtension(itemVignette.Name);  // ItemVignette.Name have twice extension (ex: .tiff.jpg)
                            string l_szExtension = Path.GetExtension(l_szFileName);
                            if (l_szExtension.ToLower().Equals(".pdf"))
                            {
                                WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                                L_oWCFServiceClient.ExplodePdfCompleted += L_oWCFServiceClient_ExplodePDFCompleted;
                                L_oWCFServiceClient.ExplodePdfAsync(l_szFileName, UserId, ServiceManager.GetLicenseKey());
                            }
                        }
                    }
                    else
                    {
                        CursorNormal(this);
                    }
                };
        }

        /// <summary>
        /// Called when [rotate left].
        /// </summary>
        private void OnRotateLeft()
        {
            ApplyRotateMenuClick(false);
            CanRotateAllFiles();
        }

        /// <summary>
        /// Called when [rotate right].
        /// </summary>
        private void OnRotateRight()
        {
            ApplyRotateMenuClick(true);
            CanRotateAllFiles();
        }

        #endregion

        #region Rotation

        /// <summary>
        /// Apply a rotation to whole items selected
        /// </summary>
        /// <param name="p_bRotateRight">apply a right rotation otherwise a left one</param>
        private void ApplyRotateMenuClick(bool p_bRotateRight)
        {
            if (ListBoxVignette.SelectedItems != null && ListBoxVignette.SelectedItems.Count > 0)
            {
                CursorWait(this);
                foreach (ImageRio itemVignette in ListBoxVignette.SelectedItems)
                {
                    string l_szFileName = Utils.RemoveExtension(itemVignette.Name);  // ItemVignette.Name have twice extension (ex: .tiff.jpg)
                    string l_szExtension = Path.GetExtension(l_szFileName);
                    if (l_szExtension.ToLower().Equals(".tif") || l_szExtension.ToLower().Equals(".tiff"))
                    {
                        // Call to know the number of pages from a document
                        WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                        L_oWCFServiceClient.GetImportCountTiffPagesAsync(l_szFileName, UserId, ServiceManager.GetLicenseKey(), Tuple.Create(l_szFileName, itemVignette, p_bRotateRight));
                        L_oWCFServiceClient.GetImportCountTiffPagesCompleted += L_oWCFServiceClient_GetImportCountTiffPagesCompleted;
                    }
                    else
                    {
                        if (l_szExtension.ToLower().Equals(".pdf"))
                        {
                            // Call to know the number of pages from a document
                            WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                            L_oWCFServiceClient.GetImportCountPdfPagesAsync(l_szFileName, UserId, ServiceManager.GetLicenseKey(), Tuple.Create(l_szFileName, itemVignette, p_bRotateRight));
                            L_oWCFServiceClient.GetImportCountPdfPagesCompleted += L_oWCFServiceClient_GetImportCountPdfPagesCompleted;
                        }
                        else
                        {
                            RotateDocumentWCFServices(DisplayRotatedThumbnail, string.Empty, l_szFileName, itemVignette.Img, p_bRotateRight, ListBoxVignette.SelectedItems.IndexOf(itemVignette), 1, true);
                        }
                    }
                }

            }

        }

        /// <summary>
        /// CallBack of 'GetCountPdfPageAsync'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void L_oWCFServiceClient_GetImportCountPdfPagesCompleted(object sender, GetImportCountPdfPagesCompletedEventArgs e)
        {
            if (e.Error != null)
            {
            }
            else
            {
                ReturnLong l_oReturnLong = e.Result;
                if (l_oReturnLong.IsValid == false)
                {
                }
                else
                {
                    Tuple<string, ImageRio, bool> l_oRet = (Tuple<string, ImageRio, bool>)e.UserState;
                    string l_sThumnailFullPath = AddThumbnailExtension(Path.Combine(ParameterStorageThumbnail, l_oRet.Item1));
                    RotateDocumentWCFServices(DisplayRotatedThumbnail, string.Empty, l_oRet.Item1, l_oRet.Item2.Img, l_oRet.Item3, ListBoxVignette.SelectedItems.IndexOf(l_oRet.Item2), 1, true, (int)e.Result.Value);
                }
            }
        }

        /// <summary>
        /// CallBack of 'GetCountTiffPageAsync'
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void L_oWCFServiceClient_GetImportCountTiffPagesCompleted(object sender, GetImportCountTiffPagesCompletedEventArgs e)
        {
            if (e.Error != null)
            {
            }
            else
            {
                ReturnLong l_oReturnLong = e.Result;
                if (l_oReturnLong.IsValid == false)
                {
                }
                else
                {
                    Tuple<string, ImageRio, bool> l_oRet = (Tuple<string, ImageRio, bool>)e.UserState;
                    string l_sThumnailFullPath = AddThumbnailExtension(Path.Combine(ParameterStorageThumbnail, l_oRet.Item1));
                    RotateDocumentWCFServices(DisplayRotatedThumbnail, string.Empty, l_oRet.Item1, l_oRet.Item2.Img, l_oRet.Item3, ListBoxVignette.SelectedItems.IndexOf(l_oRet.Item2), 1, true, (int)e.Result.Value);
                }
            }
        }

        /// <summary>
        /// DisplayRotatedThumbnail
        /// </summary>
        /// <param name="p_aRawImage">Raw image</param>
        /// <param name="p_iIndexDocumentSelected">Index of selected document</param>
        /// <param name="p_iNbOfPage">Nb of document pages</param>
        private void DisplayRotatedThumbnail(Byte[] p_aRawImage, int p_iIndexDocumentSelected, int p_iNbOfPage)
        {
            ( (ImageRio)ListBoxVignette.SelectedItems[p_iIndexDocumentSelected] ).Img = p_aRawImage;
        }

        #endregion

        #region Import several Files

        /// <summary>
        /// Imports the files.
        /// </summary>
        /// <param name="files">The files.</param>
        public void ImportFiles(IEnumerable<FileInfo> files)
        {
            bool m_bAllFilesAreClosed = true;

            // Filter files granted
            if (files != null)
            {
                foreach (var fileInfo in files)
                {

                    try
                    {
                        fileInfo.OpenRead();
                    }
                    // Catch to wait until file is completely transfered in the directory
                    catch (System.IO.IOException)
                    {
                        MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(Resx.GetLabel(ResxCommon.ERROR), Resx.GetLabel(ResxListVignetteSearch.IMPORT_FILE_ISOPEN), MessageBoxButtons.Ok, MessageBoxIcon.Error);
                        L_oMessage.Show();
                        m_bAllFilesAreClosed = false; 
                    }

                }

                if (m_bAllFilesAreClosed)
                {
                    IEnumerable<FileInfo> l_oFilesGranted =
                         files.Where(x => m_aFileFiltersGranted.Contains(Path.GetExtension(x.Name).ToUpper()) == true);

                    IEnumerable<FileInfo> l_oFilesNotGranted =
                         files.Where(x => m_aFileFiltersGranted.Contains(Path.GetExtension(x.Name).ToUpper()) == false);

                    if (files.Count() != l_oFilesGranted.Count())
                    {
                        string l_sFileNotSupported = string.Empty;
                        int l_oCpt = 0;
                        foreach (var l_ofileInfo in l_oFilesNotGranted)
                        {
                            if (l_oCpt < 4)
                            {
                                l_sFileNotSupported += "\n" + l_ofileInfo.Name;
                                l_oCpt++;
                            }
                            else
                            {
                                if (l_oFilesNotGranted.Count() > 4)
                                    l_sFileNotSupported += "\n...";
                                break;
                            }

                        }


                        CursorNormal(this);
                        MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow("Import", m_sMsgFileCompatible + l_sFileNotSupported,
                                                                                     MessageBoxButtons.Ok,
                                                                                     MessageBoxIcon.Warning);
                        L_oMessage.Show();
                    }
                    else
                    {
                        BusinessEntitiesDomainContext L_oBeDC = new BusinessEntitiesDomainContext();

                        //foreach (FileInfo l_oFileInfo in l_oFilesGranted)
                        //{
                        //    var query = L_oBeDC.AddActionHistoricQuery((int)Constant.UserActions.IMPORTATION, 0, 0, null,
                        //                                   l_oFileInfo.Name);
                        //    L_oBeDC.Load(query);
                        //}

                        PostDocuments(l_oFilesGranted);
                    }
                }
            }
        }

        #endregion

        #region PostDocuments

        /// <summary>
        /// Posts the documents.
        /// </summary>
        /// <param name="files">The files.</param>
        private void PostDocuments(IEnumerable<FileInfo> files)
        {
            try
            {
                m_oFilenamOnError = new List<string>();
                m_iNbrImportFile = 0;
                m_iNbDocToLoad = 0;
                m_iNbDocToLoad_KO = 0;
                m_iNbDocToLoad_OK = 0;

                //SplashScreen.StopCurrentAction += SplashScreen_StopCurrentAction;
                CursorWait(this);
                SplashScreenManager.SplashScreen.ProgressBarProcess.Visibility = System.Windows.Visibility.Visible;
                SplashScreenManager.SplashScreen.Message = m_sMsgIsImporting;

                if (files != null && files.Count() > 0)
                {
                    //On appel le service pour savoir si les fichiers exstent deja ou pas.
                    m_iCountPostedDocument = 0;
                    m_iNbrImportFile = files.Count();
                    m_iNbDocToLoad = files.Count();

                    m_oPostManyDocument = new PostManyDocument(UserId, files, 1024 * 1024 * 2);
                    m_oPostManyDocument.AbortImport += m_oPostManyDocument_AbortImport;
                    m_oPostManyDocument.EndOfPost += m_oPostManyDocument_EndOfPost;
                    m_oPostManyDocument.PostError += m_oPostManyDocument_PostError;
                    m_oPostManyDocument.Do(OnBeforePostDocument, OnPostManyDocumentProgress);
                }
            }
            catch
            {

                if (m_iNbDocToLoad_OK + m_iNbDocToLoad_KO == m_iNbDocToLoad)
                {
                    CursorHand(this);
                }
            }
        }

        /// <summary>
        /// Handles the PostError event of the m_oPostManyDocument control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        private void m_oPostManyDocument_PostError(object sender, EventArgs e)
        {
            CursorNormal(this);
            MessageBoxChildWindow l_oMsg = new MessageBoxChildWindow(Resx.GetLabel(ResxCommon.ERROR), Resx.GetLabel(ResxListVignetteSearch.TRANSERT_FILE_ERROR), MessageBoxButtons.Ok, MessageBoxIcon.Error);
            l_oMsg.Show();

            m_oPostManyDocument.AbortImport -= m_oPostManyDocument_AbortImport;
            m_oPostManyDocument.EndOfPost -= m_oPostManyDocument_EndOfPost;
            m_oPostManyDocument.PostError -= m_oPostManyDocument_PostError;
        }

        /// <summary>
        /// Handles the EndOfPost event of the m_oPostManyDocument control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        private void m_oPostManyDocument_EndOfPost(object sender, EventArgs e)
        {
            CursorNormal(this);
            SplashScreenManager.SplashScreen.ProgressBarProcess.Visibility = System.Windows.Visibility.Collapsed;

            if (m_iNbDocToLoad_KO != 0)
            {
                MessageBoxChildWindow l_oMsg = new MessageBoxChildWindow(m_sMsgTransferErrorHeader, string.Format(m_sMsgTransferError, m_iNbDocToLoad_KO), MessageBoxButtons.Ok, MessageBoxIcon.Error, false, Logger.Level.None, string.Join("\n", m_oFilenamOnError));
                l_oMsg.Show();
            }

            m_oPostManyDocument.AbortImport -= m_oPostManyDocument_AbortImport;
            m_oPostManyDocument.EndOfPost -= m_oPostManyDocument_EndOfPost;
            m_oPostManyDocument.PostError -= m_oPostManyDocument_PostError;
            OnEndOfImport();
        }

        /// <summary>
        /// Handles the AbortImport event of the m_oPostManyDocument control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        private void m_oPostManyDocument_AbortImport(object sender, EventArgs e)
        {
            CursorNormal(this);

            m_oPostManyDocument.AbortImport -= m_oPostManyDocument_AbortImport;
            m_oPostManyDocument.EndOfPost -= m_oPostManyDocument_EndOfPost;
            m_oPostManyDocument.PostError -= m_oPostManyDocument_PostError;
        }

        /// <summary>
        /// Called when [before post document].
        /// </summary>
        /// <param name="p_szOnPostDocument">The P_SZ on post document.</param>
        private void OnBeforePostDocument(string p_szOnPostDocument)
        {
            SplashScreenManager.SplashScreen.Message = "Import: " + ( ( m_iNbDocToLoad_OK + m_iNbDocToLoad_KO ) + 1 ) + "/" + m_iNbDocToLoad;
            SplashScreenManager.SplashScreen.MessageDetail = p_szOnPostDocument;
        }

        /// <summary>
        /// Called when [post many document progress].
        /// </summary>
        /// <param name="p_iPercentageOfDone">The p_i percentage of done.</param>
        /// <param name="p_szErrorMessage">The P_SZ error message.</param>
        /// <param name="p_oThumbNail">The p_o thumb nail.</param>
        private void OnPostManyDocumentProgress(int p_iPercentageOfDone, string p_szErrorMessage, ImageRio p_oThumbNail)
        {
            try
            {
                if (p_iPercentageOfDone >= 0)
                {
                    if (!string.IsNullOrEmpty(p_szErrorMessage))
                    {
                        throw new Exception(p_szErrorMessage);
                    }

                    if (p_iPercentageOfDone == 100)
                    {
                        // +1 document posted
                        m_iCountPostedDocument++;
                        m_iNbDocToLoad_OK++;

                        this.ImportFilesAfterLoadVignettes -= ThumbnailPanel_ImportFilesAfterLoadVignettes;

                        ImageRio l_oSearchImg = ListItemSource.Where<ImageRio>(t => t.Name.Equals(p_oThumbNail.Name)).FirstOrDefault();
                        if (l_oSearchImg != null)
                        {
                            ListItemSource[ListItemSource.IndexOf(l_oSearchImg)] = p_oThumbNail;
                        }
                        else
                        {
                            if (ServiceManager.ImportOrderByDescending)
                            {
                                ListItemSource.Insert(0, p_oThumbNail);
                            }
                            else
                            {
                                ListItemSource.Add(p_oThumbNail);
                            }

                            OnImportDocumentProgressed(ListItemSource);
                        }
                        if (ListAllDocFileName == null)
                        {
                            ListAllDocFileName = new List<string>();

                        }

                        //only if the name is not in the list
                        if (!ListAllDocFileName.Contains(Utils.RemoveExtension(p_oThumbNail.Name)))
                        {
                            if (ServiceManager.ImportOrderByDescending)
                            {
                                ListAllDocFileName.Insert(0, Utils.RemoveExtension(p_oThumbNail.Name));
                            }
                            else
                            {
                                ListAllDocFileName.Add(Utils.RemoveExtension(p_oThumbNail.Name));
                            }
                        }

                        //Select or unselect all document ifthe parameter is set in config file
                        SelectImages();

                        if (ListItemSource.Count > 0)
                        {
                            TextBlockMode.Visibility = System.Windows.Visibility.Collapsed;
                        }

                        //Progress the ProgressBar in SplashScreen
                        SplashScreenManager.SplashScreen.ProgressBarProcess.Value = ( SplashScreenManager.SplashScreen.ProgressBarProcess.Maximum * ( m_iCountPostedDocument + 1 ) ) / m_iNbDocToLoad;
                    }
                }
                else
                {
                    if (m_oFilenamOnError != null && !string.IsNullOrEmpty(p_szErrorMessage) && !m_oFilenamOnError.Contains(p_szErrorMessage))
                    {
                        m_iNbDocToLoad_KO++;
                        m_oFilenamOnError.Add(p_szErrorMessage);
                    }
                }
            }
            catch (Exception ex)
            {
                CursorNormal(this);

                MessageBoxChildWindow m = new MessageBoxChildWindow(Resx.GetLabel(ResxCommon.ERROR), ex.Message, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                m.Show();

                LoggerHelper.Send(this.GetType().Name, " OnPostManyDocumentProgress -> EXCEPTION : " + Environment.NewLine + ex.Message);
                if (m_oFilenamOnError != null && !string.IsNullOrEmpty(p_szErrorMessage) && !m_oFilenamOnError.Contains(p_szErrorMessage))
                {
                    m_iNbDocToLoad_KO++;
                    m_oFilenamOnError.Add(p_szErrorMessage);
                }
            }
        }

        /// <summary>
        /// Selects the images.
        /// </summary>
        public override void UpdateSelectImages()
        {
            if (SelectedImages != null)
            {
                List<ImageRio> selectedImageBeforeClear = new List<ImageRio>(SelectedImages);
                ListBoxVignette.SelectedItems.Clear();
                foreach (var item in selectedImageBeforeClear)
                {
                    if (!ListBoxVignette.SelectedItems.Contains(item))
                        ListBoxVignette.SelectedItems.Add(item);
                }

                _selectedImages = selectedImageBeforeClear;
            }
        }

        public void SelectImages()
        {
            //Select or unselect all document ifthe parameter is set in config file
            if (GlobalWebContext.SelectAllImageAfterImport.HasValue)
            {
                if ((ListBoxVignette != null) && (ListBoxVignette.Items.Count > 0))
                {
                    if (GlobalWebContext.SelectAllImageAfterImport.Value)
                    {
                        OnSelectAll();
                    }
                    else
                    {
                        OnSelectNone();
                    }
                }
            }
            else
            {
                //No select parameter in config file
                if (m_iSelectedViewerDocIndex != -1)
                {
                    if ((ListBoxVignette != null) && (ListBoxVignette.Items.Count > 0))
                    {
                        if (m_iSelectedViewerDocIndex < ListBoxVignette.Items.Count)
                            ListBoxVignette.SelectedIndex = m_iSelectedViewerDocIndex;

                    }
                }
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Manage state of toolbar icons following listbox thumbnails selection
        /// </summary>
        public sealed override void ManageToolbarState()
        {
            //Manage visibility of other actions
            if (_selectedImages != null)
            {
                if (_selectedImages.Count == 1)
                {
                    if (_selectedImages[0].isDirectory)
                    {
                        DocumentContextMenu.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.ImportDirectory);
                        DocumentToolbar.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.ImportDirectory);
                    }
                    else
                    {
                        DocumentContextMenu.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.Import);
                        DocumentToolbar.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.Import);
                    }
                }
                else if (_selectedImages.Count > 1)
                {
                    //Get a list of Directories and images from selection
                    var l_oListDirectories = (from img in _selectedImages where img.isDirectory select img).ToList<ImageRio>();
                    var l_oListImages = (from img in _selectedImages where !img.isDirectory select img).ToList<ImageRio>();

                    if (l_oListDirectories.Count > 0 && l_oListImages.Count > 0)
                    {
                        //mixed mode
                        DocumentContextMenu.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.None);
                        DocumentToolbar.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.None);
                    }
                    else
                    {
                        //import mode
                        DocumentContextMenu.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.Import);
                        DocumentToolbar.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.Import);
                    }
                }
                else
                {
                    //set all menus disabled
                    DocumentContextMenu.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.None);
                    DocumentToolbar.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.None);
                }

            }
            else
            {
                //set all menus disabled
                DocumentContextMenu.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.None);
                DocumentToolbar.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.None);
            }

            //Merge and explode PDF
            if (SelectedFilenames != null && SelectedFilenames.Count == 0)
            {
                DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, false);
                DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, false);
                DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.SplitPDF, false);
                DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.SplitPDF, false);
            }
            else if (SelectedFilenames != null && SelectedFilenames.Count == 1)
            {
                if (Path.GetExtension(SelectedFilenames.First()).ToLowerInvariant() == ".pdf")
                {
                    DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, false);
                    DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, false);

                    DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.SplitPDF, true);
                    DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.SplitPDF, true);
                }
                else
                {
                    DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, true);
                    DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, true);

                    DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.SplitPDF, false);
                    DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.SplitPDF, false);
                }
            }
            else if (SelectedFilenames != null && SelectedFilenames.Count > 1)
            {
                DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, true);
                DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, true);
                DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.SplitPDF, false);
                DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.SplitPDF, false);
            }

            //Split 
            if (ListBoxVignette.SelectedItems != null)
            {
                List<string> L_oListExtension = new List<string>();
                L_oListExtension.AddRange(from Enum item in EnumHelper.GetValues(typeof(Constant.ImageFileFormat))
                                          select Constant.szGetDescription(item));

                ImageRio l_oImg = ListBoxVignette.SelectedItem as ImageRio;
                if ((DocumentContextMenu.Split2.IsEnabled || DocumentContextMenu.Split3.IsEnabled) && l_oImg != null)
                {
                    string l_sExtension = Path.GetExtension(Path.GetFileNameWithoutExtension(l_oImg.Name).ToLower());
                    if (!string.IsNullOrEmpty(l_sExtension))
                    {
                        Boolean l_bSplitIsVisible = ListBoxVignette.SelectedItems.Count > 0 && ListBoxVignette.SelectedItems.Count < 2 && L_oListExtension.Contains(l_sExtension);

                        DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.Split2, l_bSplitIsVisible);
                        DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.Split3, l_bSplitIsVisible);
                    }
                    else
                    {
                        DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.Split2, false);
                        DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.Split3, false);   
                    }
                }
            }
            else
            {
                DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.Split2, false);
                DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.Split3, false);
            }

            //Return directory is activated only if the a directory is selected
            DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.ReturnDirectory, !string.IsNullOrEmpty(CurrentSelectedDirectory), true);
            DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.ReturnDirectory, !string.IsNullOrEmpty(CurrentSelectedDirectory), true);

            //Manage save modification
            DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.SaveModifications, SaveModificationEnabled);
            DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.SaveModifications, SaveModificationEnabled);

        }

        /// <summary>
        /// Determines whether this instance [can rotate all files].
        /// </summary>
        private void CanRotateAllFiles()
        {
            if ((ListBoxVignette.SelectedItems != null) && (ListBoxVignette.SelectedItems.Count > 0))
            {
                foreach (ImageRio imgSearch in ListBoxVignette.SelectedItems)
                {
                    string L_szImageSearchName = Path.GetFileNameWithoutExtension(imgSearch.Name);
                    if (Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.DOC.szGetDescription()
                    || Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.DOCX.szGetDescription()
                        //|| Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.PDF.szGetDescription()
                    || Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.PPT.szGetDescription()
                    || Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.PPTX.szGetDescription()
                    || Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.RTF.szGetDescription()
                    || Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.TXT.szGetDescription()
                    || Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.XLS.szGetDescription()
                    || Path.GetExtension(L_szImageSearchName).ToLower() == Constant.DocumentFileFormat.XLSX.szGetDescription()
                    )
                    {
                        //Logger.Write("EXCEPTION : " + Environment.NewLine + e.Error.Message, Logger.Level.Error);
                        MessageBoxChildWindow L_oMessageGetDocument = new MessageBoxChildWindow("", LabelRotateUnsupportedFile, MessageBoxButtons.Ok, MessageBoxIcon.Information);
                        L_oMessageGetDocument.Show();
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Clears the modification.
        /// </summary>
        private void ClearModification()
        {
            ModifyRotateList.Clear();
            DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.SaveModifications, SaveModificationEnabled);
            DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.SaveModifications, SaveModificationEnabled);
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Sets the actually ranking list.
        /// </summary>
        public override void SetActuallyRankingList()
        {
            var L_oActuallyRankedList = from L_oImageRio in (ObservableCollection<ImageRio>)ListBoxVignette.ItemsSource
                                        select Utils.RemoveExtension(L_oImageRio.Name);

            RankedListFromViewer = new List<string>(L_oActuallyRankedList);
        }

        /// <summary>
        /// Selects the files to import.
        /// </summary>
        /// <param name="p_oFiles">The p_o files.</param>
        /// <returns></returns>
        public bool SelectFilesToImport(ref IEnumerable<FileInfo> p_oFiles)
        {
            if (ListBoxVignette.ItemsSource != null)
            {
                SetActuallyRankingList();
            }

            m_oImportedImageFileName.Clear();
            OpenFileDialog l_oOpenFile = new OpenFileDialog();

            StringBuilder l_szFilter = new StringBuilder();
            l_szFilter.AppendFormat("Fichiers Rio (*{0})|*{1}|", String.Join(",*", m_aFileFiltersGranted), String.Join(";*", m_aFileFiltersGranted));

            foreach (string l_oItem in m_aFileFiltersGranted)
            {
                l_szFilter.AppendFormat("(*{0})|*{0}|", l_oItem);
            }

            l_szFilter.Append("(*.*)|*.*");
            l_oOpenFile.Filter = l_szFilter.ToString();

            l_oOpenFile.Multiselect = true;

            bool openFileDialogReturn = false;

            try
            {
                //Prompt dialog
                if (l_oOpenFile.ShowDialog() == true)
                {
                    openFileDialogReturn = true;

                    //Control the maximum number of files selected
                    if (l_oOpenFile.Files.Count() > MaxNumberOfFilesImported)
                    {
                        throw new InvalidOperationException();
                    }
                    else
                    {
                        p_oFiles = l_oOpenFile.Files;
                    }
                }
            }
            catch (InvalidOperationException invalidOperationException)
            {
                LoggerHelper.Send(this.GetType().Name, invalidOperationException.Message);

                MessageBoxChildWindow errorMessage = new MessageBoxChildWindow(
                    String.Empty,
                    String.Format(Resx.GetLabel(ResxListVignetteSearch.FORMAT_MSG_MAX_NUMBER_OF_FILES_IMPORTED), MaxNumberOfFilesImported),
                    MessageBoxButtons.Ok,
                    MessageBoxIcon.Warning);

                errorMessage.Show();

                openFileDialogReturn = false;
            }

            return openFileDialogReturn;
        }

        /// <summary>
        /// Translation
        /// </summary>
        public override sealed void InitLabel()
        {
            // Initialize the base class
            //Init();

            LabelExplodePdfQuestion = Resx.GetLabel(ResxCommon.EXPLODE_PDF_QUESTION);
            LabelMergePdfQuestion = Rio.Framework.Localisation.Resx.GetLabel(ResxCommon.MERGE_PDF_QUESTION);
            LabelMergePDFFormatFileError = Resx.GetLabel(ResxCommon.MERGEPDF_FORMATFILE_ERROR);
            LabelDeleteThumbnail = Resx.GetLabel(ResxCommon.DELETE_THUMBNAIL_CONFIRMATION);
            LabelSaveModificationImage = Resx.GetLabel(ResxListVignetteSearch.SAVE_MODIFICATION_CONFIRMATION);
            LabelRotateUnsupportedFile = Resx.GetLabel(ResxListVignetteSearch.ROTATE_UNSUPPORTED_FILE);

            TextBlockMode.Text = Resx.GetLabel(ResxCommon.MODE_THUMBNAIL);

            m_sMsgIsImporting = Resx.GetLabel(ResxCommon.MSG_IMPORTING);
            m_sMsgFileCompatible = Resx.GetLabel(ResxCommon.MSG_NOT_SUPPORTED_FILE);
            m_sMsgTransferErrorHeader = Resx.GetLabel(ResxListVignetteSearch.MSG_TRANSFER_ERROR_HEADER);
            m_sMsgTransferError = Resx.GetLabel(ResxListVignetteSearch.MSG_TRANSFER_ERROR);

        }

        /// <summary>
        /// Return a Document list from the selected thumbnails
        /// </summary>
        /// <returns></returns>
        public new List<Document> GetListDocumentFromSelectedThumbnails()
        {
            List<Document> L_oListDocument = new List<Document>();

            if ((ListBoxVignette.SelectedItems != null) && (ListBoxVignette.SelectedItems.Count > 0) && (ListDocument != null))
            {
                foreach (ImageRioSearch imgSearch in ListBoxVignette.SelectedItems)
                {
                    string L_szImageSearchName = imgSearch.ImageName;

                    foreach (Document doc in ListDocument)
                    {
                        if (L_szImageSearchName.Equals(doc.ImageName))
                        {
                            L_oListDocument.Add(doc);
                            break;
                        }
                    }
                }
            }

            return L_oListDocument;
        }

        /// <summary>
        /// Gets the type of the selected image of.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public override List<T> GetSelectedImage<T>()
        {
            List<T> L_oSelectedItems = new List<T>();
            if (ListBoxVignette != null && ListBoxVignette.SelectedItems.Count > 0)
            {
                foreach (T L_oImgRio in ListBoxVignette.SelectedItems)
                {
                    L_oSelectedItems.Add(L_oImgRio);
                }
            }
            return L_oSelectedItems;
        }

        /// <summary>
        /// Return a list of all ImageRio in ListBoxVignette
        /// </summary>
        /// <returns></returns>
        public List<ImageRio> GetAllItems()
        {
            List<ImageRio> L_oSelectedItems = new List<ImageRio>();
            if (ListBoxVignette != null && ListBoxVignette.Items.Count > 0)
            {
                foreach (ImageRio L_oImgRio in ListBoxVignette.Items)
                {
                    L_oSelectedItems.Add(L_oImgRio);
                }
            }
            return L_oSelectedItems;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public override void Dispose()
        {
            base.Dispose();

            if (m_oPostManyDocument != null)
            {
                m_oPostManyDocument.AbortImport -= m_oPostManyDocument_AbortImport;
                m_oPostManyDocument.EndOfPost -= m_oPostManyDocument_EndOfPost;
                m_oPostManyDocument.PostError -= m_oPostManyDocument_PostError;
                m_oPostManyDocument.Dispose();
            }
        }

        #endregion

    }
}
